package com.ktjiaoyu.controller;

import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysRoleService;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.utils.Constants;
import com.ktjiaoyu.utils.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

@Controller
@RequestMapping("/main/user")
public class SysUserController extends BaseController{
    private static final Logger LOGGER =
            LoggerFactory.getLogger(SysUserController.class);
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;

    @RequestMapping("/page")
    public String page(Model model, SysUser condition,
                       @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){
        Page<SysUser> page = null;
        try {
            // 查询用户的分页信息
            page = sysUserService.findPage(condition, pageNo, pageSize);
            // 查询所有的角色信息
            List<SysRole> roleList = sysRoleService.findAll();
            // 将分页数据、角色列表和查询条件设置到模型数据中
            model.addAttribute("pageInfo", page);
            model.addAttribute("roleList", roleList);
            model.addAttribute("condition", condition);
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 page 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "user/page";
    }

    /**
     * 跳转到save.jsp页面的接口
     */
    @GetMapping("/save")
    public String toSave(Model model) {
        List<SysRole> roleList = null;
        try {
            roleList = sysRoleService.findAll();
            // 有角色下拉框需要数据
            model.addAttribute("roleList", roleList);
            // 回显数据时需要 sysUser，这里给个空对象避免出错
            model.addAttribute("sysUser", new SysUser());
        } catch (Exception e) {
            LOGGER.error("SysUserController中的toSave方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }
    /**
     * 保存数据接口
     */
    @PostMapping("/save")
    public String doSave(SysUser sysUser,
                         @RequestParam("idPic") MultipartFile idPic,
                         @RequestParam("workPic") MultipartFile workPic) {
        // 允许的上传图片后缀
        String[] allowImageExt = {"jpg", "jpeg", "png", "gif", "bmp"};
        Set<String> include = new HashSet(Arrays.asList(allowImageExt));
        // 设置保存路径
        String uploadPath="/statics/upload/";
        String rootPath = request().getServletContext()
                .getRealPath(uploadPath);
        try {
            if(idPic!=null && !idPic.isEmpty()) {
                //1. 文件重命名：文件名的格式：随机数.文件后缀
                String fileName = idPic.getOriginalFilename();
                // 获得上传文件的扩展名
                String extension = StringUtils.getFilenameExtension(fileName);
                // 如果不包含扩展名
                if (!include.contains(extension)) {
                    throw new Exception("上传文件仅支持" + include + "扩展名！ ");
                }
                // 生成新的文件名
                String uploadFileName = UUID.randomUUID() + "." + extension;
                //2.文件存储
                File file = new File(rootPath, uploadFileName);
                // 父目录不存在是无法保存的
                if (!file.getParentFile().exists()) {
                    // 创建父目录
                    file.getParentFile().mkdirs();
                }
                //保存文件
                idPic.transferTo(file);
                //3.属性赋值
                sysUser.setIdPicPath(uploadPath + uploadFileName);
            }
            // 上传工作照
            if(workPic!=null && !workPic.isEmpty()){
                //1. 文件重命名：文件名的格式：随机数.文件后缀
                String fileName = workPic.getOriginalFilename();
                // 获得上传文件的扩展名
                String extension = StringUtils.getFilenameExtension(fileName);
                // 如果不包含扩展名
                if (!include.contains(extension)) {
                    throw new Exception("上传文件仅支持" + include + "扩展名！ ");
                }
                // 生成新的文件名
                String uploadFileName = UUID.randomUUID() + "." + extension;
                //2.文件存储
                File file = new File(rootPath, uploadFileName);
                // 父目录不存在是无法保存的
                if (!file.getParentFile().exists()) {
                    // 创建父目录
                    file.getParentFile().mkdirs();
                }
                //保存文件
                workPic.transferTo(file);
                //3.属性赋值
                sysUser.setWorkPicPath(uploadPath + uploadFileName);
            }
            // 通过父类的 session 方法获取登录用户，由于泛型自动转换无需强转
            SysUser loginUser = session(Constants.SESSION_USER);
            boolean ok = false;
            if (sysUser.getId() == null) {
                // 如果是添加用户，关联创建用户为当前登陆用户
                sysUser.setCreatedUserId(loginUser.getId());
                sysUser.setCreatedTime(new Date());
                ok = sysUserService.save(sysUser);
            } else {
                // 如果是修改用户，关联修改用户为当前登陆用户
                sysUser.setUpdatedUserId(loginUser.getId());
                sysUser.setUpdatedTime(new Date());
                ok = sysUserService.update(sysUser);
            }
            if (ok) {
                // 保存成功，跳回列表页面
                return redirect("/main/user/page");
            }
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 doSave 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }

//    @GetMapping("/view/{id}")
//    public String view(@PathVariable("id") Long id, Model model){
//        SysUser sysUser = null;
//        try {
//            sysUser = sysUserService.findById(id);
//            model.addAttribute("sysUser", sysUser);
//        } catch (Exception e) {
//            LOGGER.error("SysUserController 中的 view 方法执行发生错误。 ", e);
//            throw new RuntimeException(e);
//        }
//        return "user/view";
//    }

    @GetMapping("/{id}/view")
    @ResponseBody
    public Object view(@PathVariable("id") Long id){
        Map<String,Object> map=new HashMap<>();
        try {
            SysUser sysUser=sysUserService.findById(id);
            if (sysUser!=null){
                map.put("code",200);
                map.put("data",sysUser);
            }else {
                map.put("code",500);
            }
        }catch (Exception e) {
            LOGGER.error("SysUserController 中的 view 方法执行发生错误。 ", e);
            map.put("code",500);
        }
        return map;
    }

    /**
     * 查询用户信息并跳转修改页（共用 save.jsp)
     */
    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id, Model model) {
        SysUser sysUser = null;
        List<SysRole> roleList = null;
        try {
            sysUser = sysUserService.findById(id);
            roleList = sysRoleService.findAll();
            // 有角色下拉框需要数据
            model.addAttribute("roleList", roleList);
            // 回显数据时需要 sysUser，这里给个空对象避免出错
            model.addAttribute("sysUser", sysUser);
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 toEdit 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }

    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Object del(@PathVariable("id") Long id){
        Map<String,Object> map=new HashMap<>();
        try {
            boolean ok=sysUserService.delete(id);
            if (ok){
                map.put("code","200");
                map.put("msg","删除成功");
            }else {
                map.put("code","500");
                map.put("msg","删除失败");
            }
        }catch (Exception e) {
            LOGGER.error("SysUserController中的del方法执行发生错误。 ", e);
            map.put("code","500");
            map.put("msg","删除失败");
        }
        return map;
    }

    //查重
    @GetMapping("/accountExist")
    @ResponseBody
    public Object getByAccount(@RequestParam("account") String account){
        Map<String,Object> map=new HashMap<>();
        try {
            SysUser sysUser=sysUserService.getByAccount(account);
            if (sysUser!=null){
                map.put("exist",1);
            }else {
                map.put("exist",0);
            }
        }catch (Exception e) {
            LOGGER.error("SysUserController中的getByAccount方法执行发生错误。 ", e);
            map.put("exist",-1);
            map.put("error","服务器繁忙，请稍后再试");
        }
        return map;
    }
}